package com.example.rg1activitygameapp;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private EditText editTextName;
    private EditText editTextPwd;
    private Button buttonLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editTextName=findViewById(R.id.editTextName);
        editTextPwd=findViewById(R.id.editTextPwd);
        buttonLogin=findViewById(R.id.buttonLogin);
        readUserInfo();
        buttonLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(MainActivity.this,StateActivity.class);
                intent.putExtra("userName",editTextName.getText().toString());
                intent.putExtra("userPwd",editTextPwd.getText().toString());
                saveUserInfo();
                startActivityForResult(intent,1);
            }
        });
    }

    private void saveUserInfo()
    {
        SharedPreferences sp=getSharedPreferences("userInfo",MODE_PRIVATE);
        SharedPreferences.Editor editor=sp.edit();
        editor.putString("userName",editTextName.getText().toString());
        editor.putString("userPwd",editTextPwd.getText().toString());
        editor.apply();
        Toast.makeText(this,"用户信息保存成功！",Toast.LENGTH_SHORT).show();
    }

    private void readUserInfo()
    {
        SharedPreferences sp=getSharedPreferences("userInfo",MODE_PRIVATE);
        String name=sp.getString("userName","请输入用户名！");
        String pwd=sp.getString("userPwd","请输入用户密码！");
        editTextName.setText(name);
        editTextPwd.setText(pwd);


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UserInfo userInfo=(UserInfo) data.getSerializableExtra("userInfo");
        editTextName.setText(userInfo.getName());
        editTextPwd.setText(userInfo.getPassword());
    }
}
